
#include "StdAfx.h"

#define CMDRECO_EXP
#include "CmdRecognizer.h"


CmdRecognizer::CmdRecognizer()
:pRecognizer( NULL )
,pRecoCtxt( NULL )
,pGrammar( NULL )
,created( false )
{
}

CmdRecognizer::~CmdRecognizer()
{
	Release();
}

bool CmdRecognizer::Create( HWND hWnd, unsigned msg, wchar_t* pFileName )
{
	if( created )
		return false;

	HRESULT hr;

	hr = pRecognizer.CoCreateInstance( CLSID_SpSharedRecognizer );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	hr = pRecognizer->CreateRecoContext( &pRecoCtxt );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	hr = pRecoCtxt->SetNotifyWindowMessage( hWnd, msg, 0, 0 );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	hr = pRecoCtxt->SetInterest( SPFEI(SPEI_RECOGNITION), SPFEI(SPEI_RECOGNITION) );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	hr = pRecoCtxt->CreateGrammar( 0, &pGrammar );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	hr = pGrammar->LoadCmdFromFile( pFileName, SPLO_DYNAMIC );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}
	
	hr = pGrammar->SetRuleState( NULL, NULL, SPRS_ACTIVE );
	if( FAILED(hr) )
	{
		Release();
		return false;
	}

	created = true;
	return true;
}

void CmdRecognizer::Release()
{
	if( NULL != pGrammar )
	{
		pGrammar.Release();
		pGrammar = NULL;
	}
	if( NULL != pRecoCtxt )
	{
		pRecoCtxt.Release();
		pRecoCtxt = NULL;
	}
	if( NULL != pRecognizer )
	{
		pRecognizer.Release();
		pRecognizer = NULL;
	}

	created = false;
}

bool CmdRecognizer::IsCreated()
{
	return created;
}

bool CmdRecognizer::GetReco( wchar_t* pDest, unsigned size )
{
	HRESULT hr;

	CSpEvent ev;
	hr = ev.GetFrom( pRecoCtxt );
	if( FAILED(hr) )
	{
		return false;
	}

	if( SPEI_RECOGNITION == ev.eEventId )
	{
		CComPtr<ISpRecoResult> pResult = ev.RecoResult();
		CSpDynamicString text;
		hr = pResult->GetText( SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &text, NULL );
		if( FAILED(hr) )
		{
			return false;
		}

		CString str = text;
		if( 0 == wcscpy_s( pDest, size, str.GetBuffer() ) )
			return true;
		else
			return false;
	}
	else
		return false;

}
